package snippets;

/*
 * Button example snippet: set the default button
 *
 * For a list of all SWT example snippets see
 * http://www.eclipse.org/swt/snippets/
 */
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;

public class Snippet108 {
	static class Timer {
		private long time = 0;
		private boolean running = false;
		public long start() {
			if (!running) {
				long result = time;
				running = true;
				time = System.currentTimeMillis() - time;
				return result;
			} else {
				return System.currentTimeMillis() - time;
			}
		}
		public long getTime() {
			return running ? System.currentTimeMillis() - time : time;
		}
		public long stop() {
			if (running) {
				running = false;
				time = System.currentTimeMillis() - time;
			} 
			return time;
		}
		public void reset() {
			running = false;
			time = 0;
		}
	}
public static void main (String [] args) {
	Display display = new Display ();
	Shell shell = new Shell (display);

	final Timer timer = new Timer();

	final Text log = new Text (shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);

	Button reset = new Button (shell, SWT.PUSH);
	reset.setText ("Reset");
	reset.addSelectionListener(new SelectionAdapter() {
		public void widgetSelected(SelectionEvent e) {
			timer.reset();
			log.insert(String.format("reset%n"));
		}
	});
	Button start = new Button (shell, SWT.PUSH);
	start.setText ("Start");
	start.addSelectionListener(new SelectionAdapter() {
		public void widgetSelected(SelectionEvent e) {
			log.insert(String.format("start %s%n", timer.start()));
		}
	});
	Button time = new Button (shell, SWT.PUSH);
	time.setText ("Time");
	time.addSelectionListener(new SelectionAdapter() {
		public void widgetSelected(SelectionEvent e) {
			log.insert(String.format("time %s%n", timer.getTime()));
		}
	});
	Button stop = new Button (shell, SWT.PUSH);
	stop.setText ("Stop");
	stop.addSelectionListener(new SelectionAdapter() {
		public void widgetSelected(SelectionEvent e) {
			log.insert(String.format("stop %s%n", timer.stop()));
		}
	});
	

	
	shell.setDefaultButton (stop);
//	shell.setLayout (new RowLayout ());
	shell.setLayout (new FillLayout ());
	shell.setBounds(10, 10, 400, 400);

	shell.pack ();
	shell.open ();
	while (!shell.isDisposed ()) {
		if (!display.readAndDispatch ()) display.sleep ();
	}
	display.dispose ();
}
}